<template>
  <div class="login-container">
    <div class="container-narrow">
      <div class="text-center">
        <h1 class="title">欢迎回来</h1>
        <p class="text-mutedh">请登录您的账户</p>
      </div>

      <a-card class="login-card">
        <a-form :model="formState" name="login" @finish="onFinish" :rules="rules" layout="vertical">
          <a-form-item label="邮箱" name="email">
            <a-input v-model:value="formState.email" size="large" placeholder="请输入邮箱">
              <template #prefix>
                <UserOutlined />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item label="密码" name="password">
            <a-input-password
              v-model:value="formState.password"
              size="large"
              placeholder="请输入密码"
            >
              <template #prefix>
                <LockOutlined />
              </template>
            </a-input-password>
          </a-form-item>

          <a-form-item label="验证码" name="checkCode">
            <div class="captcha-container">
              <a-input
                v-model:value="formState.checkCode"
                size="large"
                placeholder="请输入验证码"
                style="width: 60%"
              />
              <div class="captcha-image-container">
                <img
                  v-if="captchaData"
                  :src="captchaData"
                  alt="验证码"
                  class="captcha-image"
                  @click="refreshCaptcha"
                />
                <div v-else class="captcha-placeholder" @click="refreshCaptcha">
                  <ReloadOutlined />
                  <span>点击获取验证码</span>
                </div>
              </div>
            </div>
          </a-form-item>

          <a-form-item>
            <a-button type="primary" html-type="submit" size="large" :loading="loading" block>
              登录
            </a-button>
          </a-form-item>
        </a-form>

        <div class="text-center mt-8">
          <span class="text-muted">还没有账户？</span>
          <a @click="goToRegister">立即注册</a>
        </div>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { UserOutlined, LockOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import { loginUsingPost, checkCodeUsingGet } from '@/api/accountController'
import { useUserStore } from '@/stores/user'
import { handleApiError, showError, showSuccess } from '@/utils/error'
import { VITE_WS_URL } from '@/config/env'
const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const captchaData = ref('')
const checkCodeKey = ref('')

const formState = reactive({
  email: '13840526193@163.com',
  password: '1qaz!QAZ',
  checkCode: '',
  checkCodeKey: ''
})

const rules = {
  email: [{ required: true, message: '请输入邮箱' }],
  password: [{ required: true, message: '请输入密码' }],
  checkCode: [{ required: true, message: '请输入验证码' }]
}

const onFinish = async (values: {
  email: string
  password: string
  checkCode: string
}): Promise<void> => {
  try {
    loading.value = true
    const loginData = {
      ...values,
      checkCodeKey: checkCodeKey.value
    }
    const response = await loginUsingPost(loginData)

    if (response.data.code === 200) {
      showSuccess('登录成功')
      if (response.data.data) {
        // 确保用户数据格式正确
        const userData = {
          email: values.email,
          nickName: response.data.data.nickName || values.email,
          token: response.data.data.token,
          id: response.data.data.id
        }

        console.log('登录成功，用户数据:', userData)
        userStore.login(userData)

        // 检查登录状态
        console.log('登录后状态:', userStore.isLoggedIn.value)
        console.log('用户信息:', userStore.userInfo)
        console.log('token:', `${VITE_WS_URL}?token=${response.data.data.token}`)

        window.electron.ipcRenderer.invoke('init-websocket', {
          url: `${VITE_WS_URL}?token=${response.data.data.token}`,
          userInfo: userStore.userInfo.id
        })
        // 等待状态更新后再跳转
        await nextTick()
        console.log('准备跳转到 /home')
        router.push('/home')
      }
    } else {
      showError(response.data.info || '登录失败')
      refreshCaptcha()
    }
  } catch (error) {
    const errorInfo = handleApiError(error)
    showError(errorInfo)
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}

const refreshCaptcha = async (): Promise<void> => {
  try {
    const response = await checkCodeUsingGet()

    if (response.data.code === 200 && response.data.data) {
      captchaData.value = response.data.data.checkCode
      checkCodeKey.value = response.data.data.checkCodeKey
      formState.checkCode = ''
    } else {
      showError(response.data.info || '获取验证码失败')
    }
  } catch (error) {
    const errorInfo = handleApiError(error)
    showError(errorInfo)
  }
}

const goToRegister = (): void => {
  router.push('/register')
}

onMounted(() => {
  refreshCaptcha()
})
</script>

<style scoped>
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.container-narrow {
  width: 100%;
  max-width: 420px;
  margin: 0 auto;
}

.title {
  font-size: 26px;
  font-weight: 600;
  margin-bottom: 8px;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.login-card {
  margin-top: 24px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  background: rgba(255, 255, 255, 0.98);
  border: none;
}
.text-mutedh {
  color: rgba(255, 255, 255, 0.98);
  font-size: 15px;
}
.text-muted {
  color: rgba(19, 18, 18, 0.9);
  font-size: 15px;
}

.mt-8 {
  margin-top: 8px;
}

.captcha-container {
  display: flex;
  gap: 12px;
  align-items: stretch;
}

.captcha-image-container {
  width: 40%;
  height: 40px;
  border: 1px solid var(--color-border);
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
}

.captcha-image-container:hover {
  border-color: var(--color-primary);
}

.captcha-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
}

.captcha-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--color-muted-text);
  font-size: 12px;
  gap: 4px;
}

.captcha-placeholder:hover {
  background-color: #f5f5f5;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .container-narrow {
    max-width: 100%;
    padding: 0 16px;
  }

  .login-container {
    padding: 16px;
  }

  .title {
    font-size: 22px;
  }
}
</style>
